package com.df.library.net.condition;

import com.df.library.net.handler.ProtocolSelectHandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

public class HttpDefaultProtocolPredicate implements IProtocolPredicate{
    private  final int HTTP_CHECK_LENTH = 8;
    private final List<String> HTTPMETHOD = Arrays.asList("get","post","put","head","delete","options","trance","connect");


    public HttpDefaultProtocolPredicate(){

    }

    @Override
    public boolean check(ChannelHandlerContext ctx, ByteBuf msg) {
        int len = msg.readableBytes();
        if(len<HTTP_CHECK_LENTH){
            return false;
        }
        msg.markReaderIndex();
        byte[] tempBytes = new byte[len];
        msg.readBytes(tempBytes);
        msg.resetReaderIndex();
        String checkStr = new String(tempBytes, StandardCharsets.UTF_8).toLowerCase();
        long count = HTTPMETHOD.stream().filter(m -> checkStr.startsWith(m)).count();
        if(count>0){
            return true;
        }
        return false;
    }

    @Override
    public void channelInit(ChannelHandlerContext ctx) {
        ChannelPipeline pipeline = ctx.pipeline();
        pipeline.remove(ProtocolSelectHandler.class);

        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpObjectAggregator(1024*1024));
    }
}
